package flc.ast.fragment;

import android.Manifest;
import android.app.Dialog;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.os.Handler;
import android.os.StatFs;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import flc.ast.R;
import flc.ast.activity.ApkManageActivity;
import flc.ast.activity.AudioManageActivity;
import flc.ast.activity.DocManageActivity;
import flc.ast.activity.ImgDetailActivity;
import flc.ast.activity.PicManageActivity;
import flc.ast.activity.VideoManageActivity;
import flc.ast.adapter.RecentFileAdapter;
import flc.ast.bean.MyRecentFileBean;
import flc.ast.databinding.FragmentFileBinding;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.base.BaseNoModelFragment;
import stark.common.basic.device.StorageUtil;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.IntentUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.StkPermissionHelper;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link FileFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class FileFragment extends BaseNoModelFragment<FragmentFileBinding> {

    private Dialog myEditDialog, myRenameDialog;
    private List<MyRecentFileBean> listShow = new ArrayList<>();
    private RecentFileAdapter recentFileAdapter;
    private EditText editText;
    private String selPath;


    @Override
    protected int onCreate() {
        return R.layout.fragment_file;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(getActivity(), mDataBinding.event1Container);

        mDataBinding.llPicture.setOnClickListener(this);
        mDataBinding.llVideo.setOnClickListener(this);
        mDataBinding.llAudio.setOnClickListener(this);
        mDataBinding.llDocument.setOnClickListener(this);
        mDataBinding.llApplication.setOnClickListener(this);

        mDataBinding.rvRecentFileList.setLayoutManager(new LinearLayoutManager(mContext));
        recentFileAdapter = new RecentFileAdapter();
        mDataBinding.rvRecentFileList.setAdapter(recentFileAdapter);
        recentFileAdapter.addChildClickViewIds(R.id.ivRecentFileItemEdit);
        recentFileAdapter.setOnItemChildClickListener(this);
        recentFileAdapter.setOnItemClickListener(this);

        //编辑弹框
        editDialog();
        //重命名弹框
        renameDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.llPicture://图片管理
                getPicturePermission();
                break;
            case R.id.llVideo://视频管理
                getVideoPermission();
                break;
            case R.id.llAudio://音频管理
                getAudioPermission();
                break;
            case R.id.llDocument://文件管理
                getDocPermission();
                break;
            case R.id.llApplication://应用管理
                startActivity(ApkManageActivity.class);
                break;
            //编辑弹框
            case R.id.tvDialogEditDelete://删除
                delete();
                myEditDialog.dismiss();
                break;
            case R.id.tvDialogEditShare://分享
                share();
                myRenameDialog.dismiss();
                break;
            case R.id.tvDialogEditRename://重命名
                myEditDialog.dismiss();
                myRenameDialog.show();
                break;
            //重命名
            case R.id.ivDialogRenameConfirm:
                String name = editText.getText().toString();
                if (TextUtils.isEmpty(name)) {
                    ToastUtils.showShort(getText(R.string.please_input_video_name));
                    return;
                }
                FileUtils.rename(selPath, name + "." + FileUtils.getFileExtension(selPath));
                myRenameDialog.dismiss();
                editText.setText("");
                getData();
                break;
            case R.id.ivDialogRenameCancel:
                editText.setText("");
                myRenameDialog.dismiss();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        MyRecentFileBean bean = recentFileAdapter.getItem(position);
        if (ImageUtils.isImage(bean.getPath())) {
            ImgDetailActivity.imgPath = bean.getPath();
            startActivity(ImgDetailActivity.class);
        } else {
            IntentUtil.openDoc(mContext, bean.getPath());
        }
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        switch (view.getId()) {
            case R.id.ivRecentFileItemEdit:
                selPath = recentFileAdapter.getItem(position).getPath();
                myEditDialog.show();
                break;
        }
    }

    @Override
    protected void initData() {
        StatFs statFs = StorageUtil.getInternalMemory();//内部存储
        //已使用
        long usedLong = statFs.getTotalBytes() - statFs.getAvailableBytes();
        //总内存
        long allLong = statFs.getTotalBytes();
        double percent = (double) usedLong / allLong * 100;
        mDataBinding.tvPercent.setText((int) percent + getString(R.string.percent));
        mDataBinding.tvMemorise.setText(getString(R.string.memorise, ConvertUtils.byte2FitMemorySize(allLong, 0), ConvertUtils.byte2FitMemorySize(usedLong, 0)));
        mDataBinding.tvMemoriseNum.setText(ConvertUtils.byte2FitMemorySize(usedLong, 0) + "/" + ConvertUtils.byte2FitMemorySize(allLong, 0));
        mDataBinding.pvUsed.setProgress((int) percent);
    }

    @Override
    public void onResume() {
        super.onResume();
        getData();
    }

    private void getPicturePermission() {
        StkPermissionHelper.reqManageExternalStoragePermission().reqPermissionDesc(getString(R.string.get_manage_picture_permission)).callback(new StkPermissionHelper.ACallback() {
            @Override
            public void onGranted() {
                startActivity(PicManageActivity.class);
            }
        }).request();
    }

    private void getVideoPermission() {
        StkPermissionHelper.reqManageExternalStoragePermission().reqPermissionDesc(getString(R.string.get_manage_video_permission)).callback(new StkPermissionHelper.ACallback() {
            @Override
            public void onGranted() {
                startActivity(VideoManageActivity.class);
            }
        }).request();
    }

    private void getAudioPermission() {
        StkPermissionHelper.reqManageExternalStoragePermission().reqPermissionDesc(getString(R.string.get_manage_audio_permission)).callback(new StkPermissionHelper.ACallback() {
            @Override
            public void onGranted() {
                startActivity(AudioManageActivity.class);
            }
        }).request();
    }

    private void getDocPermission() {
        StkPermissionHelper.reqManageExternalStoragePermission().reqPermissionDesc(getString(R.string.get_manage_doc_permission)).callback(new StkPermissionHelper.ACallback() {
            @Override
            public void onGranted() {
                startActivity(DocManageActivity.class);
            }
        }).request();
    }

    private void getData() {
        listShow.clear();
        List<File> files = FileUtils.listFilesInDir(PathUtils.getFilesPathExternalFirst() + Content.myRecent);
        if (files.size() > 0) {
            for (File file : files) {
                listShow.add(new MyRecentFileBean(FileUtils.getFileName(file), file.getPath(), TimeUtils.millis2String(FileUtils.getFileLastModified(file), "yyyy/MM/dd"), FileUtils.getSize(file)));
            }
        }
        if (listShow.size() > 0) {
            recentFileAdapter.setList(listShow);
            mDataBinding.rvRecentFileList.setVisibility(View.VISIBLE);
        } else {
            mDataBinding.rvRecentFileList.setVisibility(View.GONE);
        }
    }

    private void delete() {
        showDialog(getString(R.string.delete_ing));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {

                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        FileUtils.delete(selPath);
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String path) {
                        getData();
                        dismissDialog();
                        ToastUtils.showShort(getString(R.string.delete_suc));
                    }
                });
            }
        }, 1000);
    }

    private void share() {
        IntentUtil.shareFile(mContext, selPath);
    }

    //编辑弹框
    private void editDialog() {
        myEditDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_edit, null);
        myEditDialog.setContentView(inflate);
        myEditDialog.setCancelable(true);
        Window dialogWindow = myEditDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 1.0);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView delete = inflate.findViewById(R.id.tvDialogEditDelete);
        TextView share = inflate.findViewById(R.id.tvDialogEditShare);
        TextView rename = inflate.findViewById(R.id.tvDialogEditRename);
        delete.setOnClickListener(this);
        share.setOnClickListener(this);
        rename.setOnClickListener(this);
    }

    //重命名弹框
    private void renameDialog() {
        myRenameDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_rename, null);
        myRenameDialog.setContentView(inflate);
        myRenameDialog.setCancelable(true);
        Window dialogWindow = myRenameDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.8);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        ImageView cancel = inflate.findViewById(R.id.ivDialogRenameCancel);
        ImageView comp = inflate.findViewById(R.id.ivDialogRenameConfirm);
        editText = inflate.findViewById(R.id.etDialogFormatRename);
        cancel.setOnClickListener(this);
        comp.setOnClickListener(this);
    }

}